<template>
	<view class="cover_wrapper">
		<view class="p_font_24 p_flex12 p_t_96 p_b_36">
			<view class="p_color_fff">封底</view>
			<view class="p_color_fff">封面</view>
		</view>
		<view class="p_lr_24">
			<view class="cover_content p_flex2" v-show="!isCavans">
				<view class="cover_main"></view>
				<view class="cover_line"></view>
				<view class="cover_main"></view>
				<canvas :class="coverType == 1?'cover1': 'cover2'" canvas-id="myCanvas" id="myCanvas"
					@touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd"></canvas>
			</view>
			<view class="cover_content" v-show="isCavans">
				<view class="my_canvas" :class="coverType == 1?'cover_w1': 'cover_w2'" id="my-canvas">
					<image :src="imgs" class="my_draw_canvas" data-type="image" :data-url="imgs"
						:style="'width: ' + layers[0].w + 'px;height: ' + layers[0].h + 'px;left: ' + layers[0].x + 'px;top: ' + layers[0].y + 'px;'">
					</image>
				</view>
			</view>
		</view>
		<view class="bottom">
			<view class="p_flex9 p_lr_54">
				<view class="type_content p_font_26">
					<view :class="{'active': coverType == 1}" @click="getCover(1)">只需封面</view>
					<view :class="{'active': coverType == 2}" @click="getCover(2)">封面封底</view>
				</view>
				<view class="p_font_26 p_flex2">
					<view class="p_flex2" @click="getReset">
						<image src="https://dy.sykj365.com/uploads/mini/chongzhi@2x.png" class="p_img_32 p_margin_r_8"></image>
						<view class="p_color_b2">重置</view>
					</view>
					<view class="p_flex2 p_margin_l_48" @click="getSpin">
						<image src="https://dy.sykj365.com/uploads/mini/xuanzhuan@2x.png" class="p_img_32 p_margin_r_8"></image>
						<view class="p_color_b2">旋转</view>
					</view>
				</view>
			</view>
			<view class="btn_wrapper p_flex7">
				<view class="btn01 p_font_28 p_margin_r_24" @click="selectImage">{{imgs?'重新上传': '上传封面'}}</view>
				<view class="p_btn" @click="getSure">
					<view>确定</view>
				</view>
			</view>
		</view>
		<!--  -->
		<view style="width: 350rpx;height: 490rpx;position: fixed;z-index: -1;top: -10000px;" id="coverView">
			<image :src="imgs" :style="imgsType == 1?'height: 100%': 'width: 100%'"
				:mode="imgsType == 1?'heightFix': 'widthFix'" class="coverImg"></image>
		</view>
		<view style="width: 702rpx;height: 490rpx;position: fixed;z-index: -1;top: -10000px;" id="mainView">
			<image :src="imgs" :style="imgsType == 1?'height: 100%': 'width: 100%'"
				:mode="imgsType == 1?'heightFix': 'widthFix'" class="mainImg"></image>
		</view>
		<!-- 绘制图片 -->
		<canvas canvas-id="myCanvasImg" class="myCanvasImg" :class="coverType == 1?'cover_w1': 'cover_w2'"
			style="position: fixed;z-index: -99999;opacity: 0;top: -1000px;"></canvas>
	</view>
</template>

<script>
	import Wxml2Canvas from 'wxml2canvas';

	export default {
		data() {
			return {
				ctx: '',
				beginX: '',
				beginY: '',
				movedX: '',
				movedY: '',
				layers: [],
				imgs: '',
				imgsType: 1, // 1-上传的图片横向
				areaInfo: {}, // 移动区域大小
				coverType: 1, // 1-只需封面 2-封面封底
				isCavans: false,
				coverData: {},
				bianjiInfo: {},
			}
		},
		onLoad(o) {
			if (o.coverInfo) {
				let e = JSON.parse(o.coverInfo);
				this.bianjiInfo = e;
				if (e.url) {
					this.coverType = e.coverType;
					this.imgs = e.resoure;
					this.imgsType = e.imgsType;
					setTimeout(() => {
						this.getImgsInfo(e.resoure, true);
					}, 500)
				}
			}

			this.ctx = uni.createCanvasContext('myCanvas');
			this.getAreaInfo();
			
			this.getImageBig();
		},
		onShow() {

		},
		methods: {
			getAreaInfo() {
				let self = this;
				let c_ = '';
				const query = wx.createSelectorQuery();

				if (this.coverType == 1) {
					c_ = '#coverView';
				} else {
					c_ = '#mainView';
				}

				query.selectAll(c_).boundingClientRect();
				query.exec(function(res) {
					self.areaInfo.w = res[0][0].width;
					self.areaInfo.h = res[0][0].height;
				})
			},
			selectImage() {
				this.ctx.clearRect(0, 0, 750, 900); // 清除画布
				let self = this;
				uni.chooseImage({
					success: (res) => {
						uni.getImageInfo({
							src: res.tempFilePaths[0],
							success: (imgsInfo) => {
								if (imgsInfo.width > imgsInfo.height) {
									self.imgsType = 1;
								} else {
									self.imgsType = 2;
								}
								self.imgs = res.tempFilePaths[0];
								setTimeout(() => {
									self.getImgsInfo(res.tempFilePaths[0]);
								}, 100)
							}
						})
					}
				})
			},
			getImgsInfo(e, status) {
				let self = this;
				let c_ = '';

				if (this.coverType == 1) {
					c_ = '.coverImg';
				} else {
					c_ = '.mainImg';
				}

				const query = wx.createSelectorQuery();
				query.selectAll(c_).boundingClientRect();
				query.exec(function(res) {
					let w = res[0][0].width;
					let h = res[0][0].height;
					let x_ = 0;
					let y_ = 0;

					if (status) {
						// 编辑
						x_ = self.bianjiInfo.x;
						y_ = self.bianjiInfo.y;
					} else {
						x_ = (self.areaInfo.w - w) / 2;
						y_ = (self.areaInfo.h - h) / 2;
					}

					let layer = {
						type: 'photo',
						resoure: e,
						x: x_,
						y: y_,
						w: w,
						h: h,
						isDrag: false
					}

					self.imgs = e;
					self.layers[0] = layer;
					setTimeout(() => {
						self.darwImages(e, layer.x, layer.y, layer.w, layer.h);
					}, 300)
				})
			},
			darwImages(url, x, y, w, h) {
				this.ctx.drawImage(url, x, y, w, h)
				this.ctx.draw(true)
			},
			handleTouchStart(e) {
				let {
					x,
					y
				} = e.changedTouches[0]
				this.beginX = x
				this.beginY = y
				for (var i = this.layers.length - 1; i >= 0; i--) {
					if (x > this.layers[i].x && y > this.layers[i].y && x < this.layers[i].w + this.layers[i].x && y < this
						.layers[i].h + this.layers[i].y) {
						this.layers[i].isDrag = true
						let selectObj = this.layers[i]
						this.layers.splice(i, 1)
						this.layers.push(selectObj)
						console.log(selectObj)
						break
					}
				}
			},
			handleTouchMove(e) {
				if (this.layers.length != 0 && this.layers[this.layers.length - 1].isDrag == true) {
					let {
						x,
						y
					} = e.changedTouches[0]
					this.movedX = x - this.beginX
					this.movedY = y - this.beginY
					this.layers[this.layers.length - 1].x += this.movedX
					this.layers[this.layers.length - 1].y += this.movedY
					this.beginX = x
					this.beginY = y
				}
				this.ctx.clearRect(0, 0, 750, 900)
				this.layers.forEach(l => this.darwImages(l.resoure, l.x, l.y, l.w, l.h))
			},
			handleTouchEnd(e) {
				if (this.layers.length != 0) {
					this.layers[this.layers.length - 1].isDrag = false
				}
			},
			// 切换类型
			getCover(e) {
				this.coverType = e;
				this.ctx.clearRect(0, 0, 750, 900); // 清除画布
				this.getAreaInfo();
				setTimeout(() => {
					this.getImgsInfo(this.imgs);
				}, 0)
			},
			getReset() {
				this.ctx.clearRect(0, 0, 750, 900); // 清除画布
				setTimeout(() => {
					this.getImgsInfo(this.imgs);
				}, 0)
			},
			getSpin() {

			},
			// 确定
			getSure() {
				if (!this.imgs) return getApp().getMsg('请上传封面');
				this.isCavans = true;
				setTimeout(() => {
					this.getSave();
				}, 300)
			},
			getSave() {
				uni.showLoading();
				const that = this;
				const query = wx.createSelectorQuery().in(this);
				query.select('#my-canvas').fields({ // 选择需要生成canvas的范围
					size: true,
					scrollOffset: true
				}, data => {
					let width = data.width;
					let height = data.height;

					that.coverData = {
						width,
						height
					}

					setTimeout(() => {
						that.startDraw();
					}, 300);
				}).exec();
			},
			startDraw() {
				let that = this;

				// 创建wxml2canvas对象
				let drawMyImage = new Wxml2Canvas({
					element: 'myCanvasImg', // canvas的id,
					obj: that, // 传入当前组件的this
					width: that.coverData.width,
					height: that.coverData.height,
					background: '#fff', // 生成图片的背景色
					logging: true, // 日志
					scrollY: 0,
					scrollX: 0,
					useCORS: true, //跨域
					allowTaint: true,
					progress(percent) { // 进度
						// console.log(percent);
					},
					finish(url) { // 生成的图片
						console.log(url);
						
						
						uni.uploadFile({
							url: that.$api.upload,
							filePath: url,
							name: 'file',
							formData: {},
							success: (uploadFileRes) => {
								let result = JSON.parse(uploadFileRes.data);
						
								
							}
						});
						
						
						that.layers[0].coverType = that.coverType;
						that.layers[0].url = url;
						that.layers[0].imgsType = that.imgsType;
						uni.setStorageSync('coverImgData', that.layers[0]);
						uni.hideLoading();
						uni.navigateBack();
					},
					error(res) { // 失败原因
						console.log(res);

						uni.hideLoading();
						uni.showToast({
							icon: 'error',
							title: '画图失败，请重试',
							duration: 2000
						});
					}
				}, this);
				let data = {
					// 获取wxml数据
					list: [{
						type: 'wxml',
						class: '.my_canvas .my_draw_canvas', // my_canvas要绘制的wxml元素根类名， **my_draw_canvas**单个元素的类名（所有要绘制的单个元素都要添加该类名）
						limit: '.my_canvas', // 要绘制的wxml元素根类名
						x: 0,
						y: 0
					}]
				}
				// 绘制canvas
				setTimeout(() => {
					drawMyImage.draw(data, this);
				}, 300)
			},
			getImageBig() {
				uni.request({
					url: 'https://imageenhan.cn-shanghai.aliyuncs.com/', //仅为示例，并非真实接口地址。
					data: {
						Url: 'http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageenhan/MakeSuperResolutionImage/MakeSuperResolutionImage1.png',
						Mode: 'base',
						UpscaleFactor: 2
					},
					header: {
				
					},
					success: (res) => {
						console.log(res.data);
					}
				});
			}
		}
	}
</script>

<style lang="less">
	.cover_wrapper {
		width: 100%;
		min-height: 100vh;
		background-color: #222;
	}

	.cover_content {
		width: 100%;
		height: 490rpx;
		background-color: #fff;
		position: relative;
	}

	.my_canvas {
		overflow: hidden;
	}

	.cover_line {
		height: 100%;
		width: 1px;
		border-left: 1px dashed #e8e8e8;
	}

	.cover_main {
		flex: 1;
		height: 100%;
		position: relative;
	}

	.cover1,
	.cover_w1 {
		width: 350rpx;
		height: 490rpx;
		position: absolute;
		right: 0;
		top: 0;
	}

	.cover_w1 image,
	.cover_w2 image {
		position: absolute;
	}

	.cover2,
	.cover_w2 {
		width: 702rpx;
		height: 490rpx;
		position: absolute;
		right: 0;
		top: 0;
	}

	.type_content {
		display: flex;
		flex-wrap: wrap;

		view {
			color: #B2B2B2;
			padding: 8rpx 18rpx;
			border: 1px solid #3E3E3E;
			border-radius: 80rpx;
			margin: 4rpx 8rpx;
			min-width: 68rpx;
			text-align: center;

			&.active {
				color: #05B570;
			}
		}
	}

	.btn_wrapper {
		margin-top: 82rpx;
	}

	.btn01 {
		color: #05B570;
		width: 335rpx;
		height: 72rpx;
		border: 1px solid #05B570;
		border-radius: 56rpx;
		box-sizing: border-box;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.p_btn {
		width: 335rpx;
		margin: 0;
	}

	.bottom {
		position: absolute;
		bottom: 38rpx;
		width: 100%;
	}
</style>
